package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.search.config.ElasticsearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import com.guigui.common.dto.elastic.SkusElasticModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author xin
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean save(List<SkusElasticModel> elasticModels) {

        boolean status = false;
        for (SkusElasticModel elasticModel : elasticModels) {
            try {
                BulkRequest bulkRequest = new BulkRequest();
                IndexRequest source = new IndexRequest(EsConstant.PRODUCT_INDEX).id(elasticModel.getSkuId().toString()).source(JSON.toJSONString(elasticModel), XContentType.JSON);
                bulkRequest.add(source);
                BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
                status = !bulk.hasFailures();
            } catch (IOException e) {
                log.error("保存es数据失败");
            }
        }
        return status;
    }

}
